﻿(function ($) {

    var methods = {
        init: function () {
            var t = $(this), args = arguments;

            // Check whether we have already created a button for this element
            var button = t.data('button');
            if (button && button.length !== 0)
                return;

            var button = $('<div class="ui-button ui-element ui-button-enabled ">' +
				t.text() + '</div>');

            // If a callback was specified, bind it
            if (args.length !== 0) {
                button.click(function (e) {
                    // Check whether the button is disabled
                    if (button.hasClass('ui-button-enabled'))
                        args[0](e);
                });
            }
            // Hide the original element, show and memorise the fake
            t.hide();
            t.after(button);
            t.data('button', button);

            return this;
        },

        enable: function () {
            var button = $(this).data('button');
            button.addClass('ui-button-enabled');
            button.removeClass('ui-button-disabled');
            this.removeAttr('disabled');

            return this;
        },

        disable: function () {
            var button = $(this).data('button');
            button.addClass('ui-button-disabled');
            button.removeClass('ui-button-enabled');
            this.attr('disabled', 'disabled');

            return this;
        },

        destroy: function () {
            var button = $(this).data('button');
            button.remove();
            this.data('button', '')
            this.show();

            return this;
        }
    };

    $.fn.button = function (method) {

        // Choose the correct action
        if (methods[method]) {
            return methods[method].apply(this, arguments);
        } else if (typeof method === 'object' || typeof method === 'function' 
                || !method) {
            return methods.init.apply(this, arguments);
        }

    }

})(jQuery);